package cn.script.fxj;

import cn.script.fxj.bind.BindOpt;
import cn.script.fxj.bind.FxBeanFactory;
import cn.script.fxj.bind.FxBind;
import javafx.fxml.Initializable;
import javafx.scene.layout.Pane;

import java.lang.reflect.Field;
import java.net.URL;
import java.util.ResourceBundle;

public abstract class FXBaseController extends Pane implements Initializable {

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        try {
            this.bind();
            this.initLoad();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void bind() throws IllegalAccessException {
        Field[] fields = this.getClass().getDeclaredFields();
//        if (Proxy.isProxyClass(this.getClass()) || java.lang.reflect.Proxy.isProxyClass(this.getClass())) {
//            fields = this.getClass().getSuperclass().getDeclaredFields();
//        }
        for (Field field : fields) {
            FxBind fxBind = field.getAnnotation(FxBind.class);
            if (fxBind == null) {
                continue;
            }
            Class<?> type = field.getType();
            String[] binds = fxBind.value();
            Object bean = FxBeanFactory.getBean(type, new BindOpt(this, binds));
            field.setAccessible(true);
            field.set(this, bean);
        }
    }

    public void initLoad() throws Exception {

    }
}
